from zope.interface import implements, Interface

from Products.Five import BrowserView
from Products.CMFCore.utils import getToolByName
from plone.memoize.instance import memoize
from Acquisition import aq_inner
from Products.ATContentTypes.interface.image import IATImage

from my315ok.xtjxwcontents import xtjxwcontentsMessageFactory as _


class IbarsView(Interface):
    """
    bars view interface
    """

    def test():
        """ test method"""


class barsView(BrowserView):
    """
    bars browser view
    """
    implements(IbarsView)

    def __init__(self, context, request):
        self.context = context
        self.request = request

    @property
    def portal_catalog(self):
        return getToolByName(self.context, 'portal_catalog')

    @property
    def portal(self):
        return getToolByName(self.context, 'portal_url').getPortalObject()
    
    @memoize
    def fetchimage(self):
        context = aq_inner(self.context)
        catalog = getToolByName(context, 'portal_catalog')
        sepath= '/'.join(context.getPhysicalPath()) 
#        catalog = getToolByName(self.context, 'portal_catalog')        
#        sepath = '/'.join(self.context.getPhysicalPath()) 
        query = {'meta_type':('ATImage'),
                 'sort_on':'getObjPositionInParent',
                 'sort_order':'forward',
                 'path':sepath,
         'level':1,
                 }        
        sd = catalog(query)
        return sd 

    @memoize
    def barview(self,scale="large",multiline=False):
        "genarator bars html"
        headstr =''
        bodystr = ''
        items = self.imgitems_fast(scale=scale)
        try:
            lenth = len(items['titl'])
            if bool(multiline):
                for i in range(lenth):
                    headstr = headstr + '<link url="%s" /><title text="%s"> </title>' % (items['url'][i],items['titl'][i])
                    bodystr = bodystr + '<div class="banner"><a href="%s"><img src="%s" alt="%s" />%s</a></div>' % (items['url'][i],items['src'][i],items['titl'][i],items['txt'][i])
                
            else:
                for i in range(lenth):
                    headstr = headstr + '<link url="%s" /><title text="%s"> </title>' % (items['url'][i],items['titl'][i])
                    bodystr = bodystr + '<div class="banner"><a href="%s"><img src="%s" alt="%s" /></a></div>' % (items['url'][i],items['src'][i],items['titl'][i])
        except:
            pass
        bars = {}
        bars['hstr'] = headstr
        bars['bstr'] = bodystr
        return bars
    def splittxt(self,dsp,tab):
        
        """roll zone can display multiline text,text come from current object's description,using ',' to divide line """
        if dsp == None:
            return None
        try:
            dsplist = dsp.split(tab)
        except:
            dsplist = dsp.split(",")
        k = len(dsplist)
        sp1 = "<span>"
        sp2 = "</span>"
        dsptxt = "<div class='rollzonetxt'>"
        dsptxtend = "</div>"
        for j in range(k):
            dsptxt = dsptxt + sp1 + dsplist[j] + sp2            
        dsptxt = dsptxt + dsptxtend
        return dsptxt       
                    
    @memoize
    def imgitems_fast(self,scale="large",tab=u"，"):
        brains = self.fetchimage()
        items = {}
        items['titl'] = []
        items['url'] = []
        items['src'] = []
        items['txt'] = []
        if scale == "orig":
            for bn in brains:
                base = bn.getURL()                
                items['titl'].append(bn.Title)
                dsp = self.splittxt(bn.Description, tab)
                items['txt'].append(dsp)
#                if type(bn.link2) =="Missing":
#                    url = ""
#                else:
#                    url = bn.link2
                items['url'].append(base + "/image_large")
                items['src'].append(base + "/image")          
            return items
        else:            
            for bn in brains:
                base = bn.getURL()
                items['titl'].append(bn.Title)
                dsp = self.splittxt(bn.Description, tab)
                items['txt'].append(dsp)
#                if type(bn.link2) =="Missing":
#                    url = ""
#                else:
#                    url = bn.link2
                items['url'].append(base + "/image_large")
                items['src'].append(base + "/image_" + scale)          
            return items